package com.goa.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 设置值
    public void setValue(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    // 设置带过期时间的值
    public void setValueWithExpire(String key, Object value, long timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    // 获取值
    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    // 删除值
    public void deleteValue(String key) {
        redisTemplate.delete(key);
    }

    // 检查键是否存在
    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    // 设置 Hash 值
    public void hSet(String hashKey, String key, Object value) {
        redisTemplate.opsForHash().put(hashKey, key, value);
    }

    // 获取 Hash 值
    public Object hGet(String hashKey, String key) {
        return redisTemplate.opsForHash().get(hashKey, key);
    }

    // 删除 Hash 值
    public void hDelete(String hashKey, String key) {
        redisTemplate.opsForHash().delete(hashKey, key);
    }

    // 获取所有 Hash 值
    public Map<Object, Object> hGetAll(String hashKey) {
        return redisTemplate.opsForHash().entries(hashKey);
    }
}
